import { defineStore } from 'pinia'
import type { DormitoryInspectionRecord } from '../types/DormitoryInspectionRecord'

/**
 * 寝室检查记录存储模块
 * 负责管理寝室检查相关数据的全局状态
 */
export const useDormitoryInspectionRecordStore = defineStore('dormitoryInspectionRecord', {
    // 持久化配置
    persist: {
        storage: localStorage,
        paths: ['dormitoryInspectionRecordList', 'currentDormitoryInspectionRecord']
    },
    // 状态定义
    state: () => ({
        // 所有寝室检查记录列表
        dormitoryInspectionRecordList: [] as DormitoryInspectionRecord[],

        // 当前查看的检查记录
        currentDormitoryInspectionRecord: null as DormitoryInspectionRecord | null,

        // 加载状态标记
        loading: false
    }),

    // 操作方法
    actions: {
        /**
         * 获取所有寝室检查记录
         */
        async fetchAllDormitoryInspectionRecord() {
            this.loading = true
            try {
                // 实际调用API获取检查记录
                // this.dormitoryInspectionRecordList = await inspectionApi.getAllRecords()
            } finally {
                this.loading = false
            }
        },

        /**
         * 创建新的寝室检查记录
         * @param newRecord - 新的检查记录对象
         */
        createDormitoryInspectionRecord(newRecord: DormitoryInspectionRecord) {
            this.dormitoryInspectionRecordList.unshift(newRecord)  // 添加到数组开头
        },

        /**
         * 根据问题类型筛选记录
         * @param problemType - 问题类型(1-安全问题，2-卫生问题，3-其他问题)
         * @returns 符合问题类型的记录数组
         */
        getRecordsByProblemType(problemType: number) {
            return this.dormitoryInspectionRecordList.filter(r => r.problemType === problemType)
        }
    },

    // 计算属性
    getters: {
        /**
         * 获取最近5条检查记录（用于仪表盘展示）
         * @returns 最新的5条记录数组
         */
        recentRecords(state): DormitoryInspectionRecord[] {
            return this.dormitoryInspectionRecordList.slice(0, 5)
        },

        /**
         * 根据卫生状况筛选记录
         * @param hygieneStatus - 卫生状况(1-良好，2-一般，3-较差)
         * @returns 符合卫生状况的记录数组
         */
        recordsByHygieneStatus: (state) => (hygieneStatus: number) =>
            state.dormitoryInspectionRecordList.filter(r => r.hygieneStatus === hygieneStatus)
    }
})
